/*
 * @Description: Stay hungry,Stay foolish
 * @Author: Huccct
 * @Date: 2023-05-20 10:58:16
 * @LastEditors: Huccct
 * @LastEditTime: 2023-06-02 11:27:32
 */
import { defineStore } from 'pinia'

import {
  reqLogin,
  reqLogOut,
} from '@/api/user'
import type { LoginFormData } from '@/api/user/type'
import { constantRoute } from '@/router/routes'
import {
  GET_TOKEN,
  REMOVE_TOKEN,
  SET_TOKEN,
} from '@/utils/token'
import wsManager from '@/utils/websocket'

import type { UserState } from './types/types'

function filterAsyncRoute(asyncRoute: any, routes: any) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}

const useUserStore = defineStore('User', {
  // 小仓库存储数据的地方
  state: (): UserState => {
    return {
      token: GET_TOKEN() || '',
      menuRoutes: constantRoute,
      username: '',
      avatar: '',
      userid: '',
      buttons: [],
    }
  },
  // 异步|逻辑的地方
  actions: {
    // 连接WebSocket
    connectWebSocket(id: string | undefined) {
      try {
        // 获取基础URL,替换为你的WebSocket地址
        const baseUrl = import.meta.env.VITE_APP_BASE_API?.replace('http', 'ws')
        const wsUrl = `${baseUrl}/chat/${id}`
        
        console.log('正在连接WebSocket:', wsUrl)
        wsManager.connect(wsUrl, this.token || undefined)
      } catch (error) {
        console.error('WebSocket连接失败:', error)
      }
    },

    // 断开WebSocket连接
    disconnectWebSocket() {
      wsManager.disconnect()
    },

    //用户登录方法
    async userLogin(data: LoginFormData) {
      const res = await reqLogin(data)
      // success=>token
        console.log(res)
      // error=>error.message
      if (res.code === 2000) {
        this.token = res.msg as string
        // console.log(this.token,'lll');
        this.username = data.username as string
        this.userid = res.data as string
        // 持久化
        SET_TOKEN(res.msg as string)
        
        // 登录成功后连接WebSocket
        this.connectWebSocket(res.data)

    
        
        return 'ok'
      } else {
        // return res.msg as string
        return Promise.reject(new Error(res.msg as string))
      }
    },
    async userInfo() {
      // const res: userInfoResponseData = await reqUserInfo(userid)
      //   console.log(res.data)

      // if (res.code === 2000) {
        
      //   this.username = res.data.name as string
      //   // this.avatar = res.data.avatar as string
      //   // this.buttons = res.data.buttons

      //   // const userAsyncRoute = filterAsyncRoute(
      //   //   cloneDeep(asyncRoute),
      //   //   res.data.routes,
      //   // )
        this.menuRoutes = [...constantRoute]
      //   // [...userAsyncRoute, anyRoute].forEach((route: any) => {
      //   //   console.log(route)

      //   //   router.addRoute(route)
      //   //   console.log('router', router)
      //   // })
        return 'ok'
      // } else {
      //   return Promise.reject(new Error(res.message))
      // }
    },
    async userLogout() {
      const res = await reqLogOut( this.userid)
      if (res.code === 2000) {
        // 登出前断开WebSocket连接
        this.disconnectWebSocket()
        
        this.token = ''
        this.username = ''
        this.userid = ''
        // this.avatar = ''
        REMOVE_TOKEN()
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
  },
  getters: {},
})

export default useUserStore
